﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;
using XHD.DBUtility;

namespace XHD.Server
{
    public class Product
    {
        public static BLL.Product product = new BLL.Product();
        public static Model.Product model = new Model.Product();
        public static BLL.Sys_Param sp = new BLL.Sys_Param();
        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        public static BLL.Product_Customer_Price bll = new BLL.Product_Customer_Price();
        public static Model.Product_Customer_Price modelPrice = new Model.Product_Customer_Price();

        public Product()
        {
        }

        public Product(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            int version = userinfo.GetCurrentVersion(context);
            if (version == 1)
            {
                employee = userinfo.GetCurrentEmpInfo(context);
                emp_id = employee.id;
                emp_name = PageValidate.InputText(employee.name, 50);
                uid = PageValidate.InputText(employee.uid, 50);
            }
            else if (version == 2)
            {
                var e = userinfo.GetCurrentCusInfo(context);
                emp_id = e.id;
                emp_name = PageValidate.InputText(e.cus_name, 50);
                uid = PageValidate.InputText(e.account, 50);

            }

        }

        public string save()
        {
            model.category_id = PageValidate.InputText(request["T_product_category_val"], 50);
            model.product_name = PageValidate.InputText(request["T_product_name"], 255);
            model.specifications_id = PageValidate.InputText(request["T_specifications_val"], 255);
            model.specifications = PageValidate.InputText(request["T_specifications"], 255);
            model.unit_id = PageValidate.InputText(request["T_product_unit_val"],255);
            model.unit = PageValidate.InputText(request["T_product_unit"], 255);
            model.remarks = PageValidate.InputText(request["T_remarks"], 255);
            model.price = StringPlus.str2dec(request["T_price"]);
            model.agio = StringPlus.str2dec(request["T_agio"]);
            model.cost = StringPlus.str2dec(request["T_cost"]);
             model.WaitDay = StringPlus.str2int(request["T_waitDay"]); 
            model.dailyoutput = StringPlus.str2int(request["T_dailyoutput"]);
            model.pickcycle = StringPlus.str2int(request["T_pickcycle"]);
            model.dosageUnit_id = PageValidate.InputText(request["T_jldw_val"], 255);
            model.dosageUnit = PageValidate.InputText(request["T_jldw"], 255);
            model.Series_Id = PageValidate.InputText(request["T_px_val"], 255);
            model.Series_Name = PageValidate.InputText(request["T_px"], 255);
            model.Level_Id = PageValidate.InputText(request["T_dj_val"], 255);
            model.Level_Name = PageValidate.InputText(request["T_dj"], 255);
            model.Img = PageValidate.InputText(request["headurl"], 255);
            model.RichText= PageValidate.InputText(request["richText"], int.MaxValue);

            model.EffectiveSperm = StringPlus.str2dec(request["T_EffectiveSperm"]);
            model.Quantity = StringPlus.str2dec(request["T_Quantity"]);
            model.Dose = StringPlus.str2dec(request["T_Dose"]);
            string pid = PageValidate.InputText(request["pid"], 50);
            if (PageValidate.checkID(pid))
            {
                model.id = pid;
                DataSet ds = product.GetList($" id= '{pid}' ");
                if (ds.Tables[0].Rows.Count == 0)
                    return XhdResult.Error("参数不正确，更新失败！").ToString();

                DataRow dr = ds.Tables[0].Rows[0];
                product.Update(model);

                string UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.product_name;
                string EventType = "产品修改";
                string EventID = model.id;

                string Log_Content = null;

                if (dr["category_name"].ToString() != request["T_product_category"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品类别", dr["category_name"],
                        request["T_product_category"]);

                if (dr["product_name"].ToString() != request["T_product_name"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品名字", dr["product_name"],
                        request["T_product_name"]);

                if (dr["specifications"].ToString() != request["T_specifications"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品规格", dr["specifications"],
                        request["T_specifications"]);

                if (dr["unit"].ToString() != request["T_product_unit"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "单位", dr["unit"], request["T_product_unit"]);

                if (dr["remarks"].ToString() != request["T_Remark"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "备注", dr["remarks"], request["T_Remark"]);

                if (decimal.Parse(dr["price"].ToString()) != decimal.Parse(request["T_price"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "零售价", dr["price"], request["T_price"]);

                if (decimal.Parse(dr["cost"].ToString()) != decimal.Parse(request["T_cost"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "成本价", dr["cost"], request["T_cost"]);

                if (decimal.Parse(dr["agio"].ToString()) != decimal.Parse(request["T_agio"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "折扣价", dr["agio"], request["T_agio"]);
                if (int.Parse(dr["pickcycle"].ToString()) != decimal.Parse(request["T_pickcycle"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "采集周期", dr["pickcycle"], request["T_pickcycle"]);

                if (decimal.Parse(dr["dailyoutput"].ToString()) != decimal.Parse(request["T_dailyoutput"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "每日产量", dr["dailyoutput"], request["T_dailyoutput"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.create_id = emp_id;
                model.create_time = DateTime.Now;
                model.id = Guid.NewGuid().ToString();
                model.barcode = sp.GetBarCode("PRODUCT");
                product.Add(model);
            }

            return XhdResult.Success().ToString();
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " create_time";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["categoryid"]))
                serchtxt += $" and category_id='{PageValidate.InputText(request["categoryid"], 50)}'";

            if (!string.IsNullOrEmpty(request["stext"]))
                serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";
            string dt = "";
            string type = request["type"];
            if (!string.IsNullOrEmpty(type)) {
                if (type == "Online")
                {
                    string cid = emp_id;
                DataSet ds1 = product.GetListOnline(PageSize, PageIndex, serchtxt, sorttext,cid, out Total);

                      dt = GetGridJSON.DataTableToJSON1(ds1.Tables[0], Total);

                }
            }
            if (dt == "")
            {
                //权限
                DataSet ds = product.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

                dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            }
            return (dt);
        }

        public string gridPrice()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " createTime";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["pid"]))
                serchtxt += $" and product_id='{PageValidate.InputText(request["pid"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";
          
            //权限
            DataSet ds = bll.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }
        public string formPrice(string pid,string cid)
        {
            if (!PageValidate.checkID(cid)) return "{}";
            cid = PageValidate.InputText(cid, 50);
            pid = PageValidate.InputText(pid, 50);
            DataSet ds = bll.GetList($" product_id= '{pid}' AND customer_id='{cid}' ");
            return DataToJson.DataToJSON(ds);

        }
        public string savePrice()
        {
            modelPrice.product_id = PageValidate.InputText(request["pid"], 50);
            modelPrice.price = StringPlus.str2dec( PageValidate.InputText(request["T_Price"], 50));
            modelPrice.remarks = PageValidate.InputText(request["T_remarks"], 50); 
            string customer_id = PageValidate.InputText(request["cid"], 50);
            modelPrice.customer_id = customer_id;
            if (bll.Exists(modelPrice.product_id, modelPrice.customer_id))
            { 
                modelPrice.createName = emp_name;
                modelPrice.createTime = DateTime.Now;
                bll.Update(modelPrice);
                 
            }
            else
            {
                modelPrice.createName = emp_name;
                modelPrice.createTime = DateTime.Now; 
                bll.Add(modelPrice);
            }

            return XhdResult.Success().ToString();
        }
        public string delPrice(string cid, string pid)
        {
            if (!PageValidate.checkID(cid)) return XhdResult.Error("参数错误！").ToString();
            cid = PageValidate.InputText(cid, 50);
            pid = PageValidate.InputText(pid, 50); 

            bool isdel = bll.Delete(pid, cid);
            if (!isdel) return XhdResult.Error("系统错误，删除失败！").ToString();

       
            return XhdResult.Success().ToString();

        }


        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = product.GetList($" id= '{id}' ");
            return DataToJson.DataToJSON(ds);

        }
        public string tree()
        {
            DataSet ds = product.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString("root", ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }
        public string combo(string id)
        {
            DataSet ds = product.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            //str.Append("{\"id\":\"root\",\"text\":\"无\",\"d_icon\":\"\"},");
            str.Append(GetTreeString(id, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return XhdResult.Error("参数错误！").ToString();
            id = PageValidate.InputText(id, 50);
            DataSet ds = product.GetList($" id= '{id}' ");
            if (ds.Tables[0].Rows.Count < 1)
                return XhdResult.Error("系统错误，无数据！").ToString();

            var ccod = new BLL.Sale_order_details();
            if (ccod.GetList($"product_id = '{id}'").Tables[0].Rows.Count > 0)
                return XhdResult.Error("此产品下含有订单，不允许删除！").ToString();

            

            bool candel = true;
            if (uid != "admin")
            {
                //controll auth
                var getauth = new GetAuthorityByUid();
                candel = getauth.GetBtnAuthority(emp_id.ToString(), "FDE2E0EE-D2B1-40BD-928F-AB28F58D770D");
                if (!candel)
                    return XhdResult.Error("无此权限！").ToString();
            }

            bool isdel = product.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误，删除失败！").ToString();

            //日志
            string EventType = "产品删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = ds.Tables[0].Rows[0]["product_name"].ToString();



            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }



        public string Base64Upload()
        {
            string base64txt = request["base64img"];
            string ext = "png";
            //处理文件头
            if (string.IsNullOrEmpty(base64txt))
                return null;

            int i = base64txt.IndexOf("image") + 6;
            int j = base64txt.IndexOf("base64");

            if (i > -1 && j - i - 1 > 0)
            {
                ext = base64txt.Substring(i, j - i - 1);
            }
            base64txt = base64txt.Substring(base64txt.IndexOf(',') + 1);

            Random rnd = new Random();
            string nowfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(10000, 99999) + "." + ext;

            string filetype = PageValidate.InputText(request["Type"], 50);
            string id = PageValidate.InputText(request["id"], 50);

            string path = @"/Images/upload/product/" ;
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

            path = path + nowfileName;
            //过滤特殊字符
            string dummyData = base64txt.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }
            string sql = "UPDATE Product SET	 img='"+ nowfileName + "' WHERE id='"+id+"'";
            DbHelperSQL.ExecuteSql(sql);
            StringToFile(dummyData, HttpContext.Current.Server.MapPath(path));

            return XhdResult.Success(nowfileName).ToString();
        }

        public object RichUpload()
        {
            HttpPostedFile uploadFile = request.Files[0];
            string filename = uploadFile.FileName;
            string sExt = filename.Substring(filename.LastIndexOf(".")).ToLower();
            DateTime now = DateTime.Now;
            string nowfileName = now.ToString("yyyyMMddHHmmss") + Assistant.GetRandomNum(6) + sExt;
    
            string ServerUrl = $"~/Images/upload/product/Rich/";
            var savePath = HttpContext.Current.Server.MapPath(ServerUrl);

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                }
            }
            catch (Exception ex)
            {
                Controller.IO.LogManager.Add(ex.ToString());
            }

            string path = $"~/Images/upload/product/Rich/" + nowfileName;

            uploadFile.SaveAs(HttpContext.Current.Server.MapPath(path));
            string imgurl = PubConstant.GetConnectionString("smallAppImgUrl");
            object o = new
            {
                errno = 0, // 注意：值是数字，不能是字符串
                data = new
                {
                    url = imgurl+"Images/upload/product/Rich/" + nowfileName, // 图片 src ，必须
                    alt= "yyy", // 图片描述文字，非必须
                   href="zzz" // 图片的链接，非必须
                }
            };

            //string ss = {
            //                "errno": 0, // 注意：值是数字，不能是字符串
            //                "data": {
            //                "url": "xxx", // 图片 src ，必须
            //                "alt": "yyy", // 图片描述文字，非必须
            //                "href": "zzz" // 图片的链接，非必须
            //                }
            //                };
            return StringToJson.ObjectToJson(o);// "{\"errno\":0,data:{\"url\":\"http://localhost:58036/Images/upload/product/Rich/" + nowfileName+"\"}}";
             
        }

        public object RichUploadBase64()
        {
            string base64txt = request["base64img"];
            string ext = "png";
            //处理文件头
            if (string.IsNullOrEmpty(base64txt))
                return null;

            int i = base64txt.IndexOf("image") + 6;
            int j = base64txt.IndexOf("base64");

            if (i > -1 && j - i - 1 > 0)
            {
                ext = base64txt.Substring(i, j - i - 1);
            }
            base64txt = base64txt.Substring(base64txt.IndexOf(',') + 1);

            Random rnd = new Random();
            string nowfileName = "rich-"+DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(10000, 99999) + "." + ext;

            string filetype = PageValidate.InputText(request["Type"], 50);

            string path = @"/Images/upload/product/";
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

            path = path + nowfileName;
            //过滤特殊字符
            string dummyData = base64txt.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }

            StringToFile(dummyData, HttpContext.Current.Server.MapPath(path));
            object o = new
            {
                 errno=0, // 注意：值是数字，不能是字符串
                 data= new{
                 url= "xxx", // 图片 src ，必须
                //"alt": "yyy", // 图片描述文字，非必须
                //"href": "zzz" // 图片的链接，非必须
                }
             };

            return o;
        } 
        /// <summary>  
        /// 把经过base64编码的字符串保存为文件  
        /// </summary>  
        /// <param name="base64String">经base64加码后的字符串 </param>  
        /// <param name="fileName">保存文件的路径和文件名 </param>  
        /// <returns>保存文件是否成功 </returns>  
        private static bool StringToFile(string base64String, string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
            {
                bw.Write(Convert.FromBase64String(base64String));
            }
            bw.Close();
            fs.Close();
            return true;
        }


        private static string GetTreeString(string Id, DataTable table)
        {
            DataRow[] rows = table.Select("1=1");

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                string icon = "images/icon/11.png"; 
                str.Append("{\"id\":\"" + (string)row["id"] + "\",\"text\":\"" + (string)row["product_name"] + "\",\"specifications\":\"" + (string)row["specifications"] + "\",\"d_icon\":\"../../" + icon + "\"");

                //if (GetTreeString((string)row["id"], table).Length > 0)
                //{
                //    str.Append(",\"children\":[");
                //    str.Append(GetTreeString((string)row["id"], table));
                //    str.Append("]},");
                //}
                //else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }

    }
}
